package com.dxx.cloud.admin.service.sms.impl;

import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.aliyun.tea.TeaException;
import com.aliyun.teaopenapi.models.Config;
import com.aliyun.teautil.models.RuntimeOptions;
import com.dxx.cloud.admin.config.AliSmsProperties;
import com.dxx.cloud.admin.module.entity.sms.MsgSend;
import com.dxx.cloud.admin.module.entity.sms.MsgTemplate;
import com.dxx.cloud.admin.module.request.sms.SmsRequest;
import com.dxx.cloud.admin.service.sms.IMsgSendService;
import com.dxx.cloud.admin.service.sms.IMsgTemplateService;
import com.dxx.cloud.admin.service.sms.ISmsService;
import com.google.gson.Gson;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.dromara.common.core.exception.ServiceException;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.Date;
import java.util.Map;

@Service
@Slf4j
public class SmsServiceImpl implements ISmsService {
    @Resource
    private AliSmsProperties aliSmsConfig;

    @Resource
    private IMsgTemplateService msgTemplateService;

    @Resource
    private IMsgSendService msgSendService;

    @Resource
    private Gson gson;

    @Override
    public boolean smsCheckMsg(SmsRequest request) throws Exception {
        boolean ret = false;
        Config config = new Config().setEndpoint(aliSmsConfig.getEndPoint()).setAccessKeyId(aliSmsConfig.getAccessKeyId()).setAccessKeySecret(aliSmsConfig.getAccessKeySecret());
        Client client = new Client(config);
        final MsgTemplate msgTemplate = msgTemplateService.getById(request.getTemplateId());
        // 软删除未起作用
        if (null == msgTemplate || msgTemplate.getIsDeleted() == 1) {
            log.info("短信模板不存在:{}", request);
            return true;
        }
        SendSmsRequest sendSmsRequest = new SendSmsRequest().setPhoneNumbers(request.getPhoneNumbers()).setSignName(aliSmsConfig.getSignName()).setTemplateCode(msgTemplate.getCode());

        sendSmsRequest.setTemplateParam(gson.toJson(request.getParams()));

        RuntimeOptions runtime = new RuntimeOptions();
        String result = null;
        try {
            // 复制代码运行请自行打印 API 的返回值
            String[] phoneNumbers = request.getPhoneNumbers().split(",");
            boolean whileListFlag = Arrays.stream(phoneNumbers).allMatch(aliSmsConfig.getSmsWhiteList()::contains);

//            if ("prod".equals(SpringUtils.getActiveProfile()) || whileListFlag) {
            if (true) {
                SendSmsResponse sendSmsResponse = client.sendSmsWithOptions(sendSmsRequest, runtime);
                log.info(sendSmsResponse.toString());
                log.info(String.format("%s 手机号:%s ,tepmlateParam:%s, 结果:%s", sendSmsRequest.getTemplateCode(), request.getPhoneNumbers(), sendSmsRequest.getTemplateParam(), sendSmsResponse.getBody().getMessage()));
                if (null != sendSmsResponse.getBody()) {
                    result = sendSmsResponse.getBody().getMessage();
                }
                if (null != sendSmsResponse.getBody() && "OK".equalsIgnoreCase(sendSmsResponse.getBody().getMessage())) {
                    ret = true;
                }
            }
        } catch (Exception _error) {
            TeaException error = new TeaException(_error.getMessage(), _error);
            // 错误 message
            log.error("短信异常", _error);
            // 诊断地址
            log.error(String.valueOf(error.getData().get("Recommend")));
            throw new ServiceException("短信发送失败");
        } finally {
            final MsgSend msgSend = new MsgSend();
            msgSend.setPhone(request.getPhoneNumbers());
            msgSend.setTemplateId(request.getTemplateId());
            msgSend.setTemplateParam(sendSmsRequest.getTemplateParam());
            msgSend.setResult(result);
            msgSend.setCreated(new Date());
            msgSendService.save(msgSend);
        }
        return ret;
    }

    @Override
    public boolean smsCodeMsg(String phone, String code) throws Exception {
        return smsCheckMsg(new SmsRequest(phone, 1L, Map.of("code", code)));
    }

    @Override
    public boolean smsCodeMsg(Integer countryCode, String phone, String code) throws Exception {
        return false;
    }
}
